package com.tianyu.inspection.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tianyu.inspection.common.HttpRequest;
import com.tianyu.inspection.common.model.PageModel;
import com.tianyu.inspection.service.api.IFlyTaskService;
import com.tianyu.inspection.service.telemetry.yukong.YkClient;
import com.tianyu.inspection.common.component.AppConstants;
import com.tianyu.inspection.common.component.MapperModel;
import com.tianyu.inspection.entity.Danger;
import com.tianyu.inspection.entity.FlyTask;
import com.tianyu.inspection.entity.User;
import com.tianyu.inspection.entity.model.OperateMo;
import com.tianyu.inspection.entity.model.QueryMo;
import com.tianyu.inspection.mapper.DangerMapper;
import com.tianyu.inspection.mapper.FlyTaskMapper;
import io.ocs.model.OcsSimpleModel;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**********************************
 * @Author YSW
 * @Description 航线服务
 * @Date 2021/1/11 - 15:59
 **********************************/

@Service
public class FlyTaskServiceImpl implements IFlyTaskService {

    @Resource
    private FlyTaskMapper flyTaskMapper;

    @Resource
    private DangerMapper dangerMapper;

    @Resource
    private AppConstants appConstants;

    @Resource
    private MapperModel mapperModel;

    @Resource
    private OcsSimpleModel ocsSimpleModel;

    /**
     * 飞行统计
     *
     * @param queryMo 查询参数
     * @return 是否操作成功
     */
    @Override
    public ModelMap flightStatistics(QueryMo queryMo) {
        return flyTaskMapper.flightStatistics(queryMo.getEqMap());
    }

    /**
     * 分页查询
     *
     * @param queryMo 筛选参数
     * @return ModelMap
     */
    @Override
    public IPage<FlyTask> searchListPage(QueryMo queryMo) {
        Map<Integer, String> pipelineMap = mapperModel.getPipelineMap(queryMo);
        Map<Integer, User> userMap = mapperModel.getUserMap(queryMo.getEqMap().get("project_id"),5);
        Object startTime = queryMo.get("startTime");
        Object endTime = queryMo.get("endTime");
        Object taskName = queryMo.get("taskName");
        queryMo.getEqMap().remove("start_time");
        queryMo.getEqMap().remove("end_time");
        queryMo.getEqMap().remove("task_name");
        QueryWrapper<FlyTask> wrapper = PageModel.getModelWrapper(queryMo);
        if (Objects.nonNull(startTime) && !Objects.equals(startTime, "")){
            wrapper.ge("start_time",startTime);
        }
        if (Objects.nonNull(endTime) && !Objects.equals(endTime, "")){
            wrapper.le("start_time",endTime);
        }
        if (Objects.nonNull(taskName) && !Objects.equals(taskName, "")){
            wrapper.like("task_name",taskName);
        }
        Page<FlyTask> flyTaskPage = new Page<FlyTask>().setSize(queryMo.getPageSize()).setCurrent(queryMo.getPageNum());
        IPage<FlyTask> modelPage = PageModel.getModelPage(wrapper,flyTaskPage,flyTaskMapper);
        modelPage.getRecords().forEach(flyTask -> {
            final Integer userId = flyTask.getUserId();
            final Integer pipelineId = flyTask.getPipelineId();
            final String telemetryUrl = flyTask.getTelemetryUrl();
            flyTask.setDangerCount(Math.toIntExact(dangerMapper.selectCount(new QueryWrapper<Danger>()
                    .eq("fly_task_id", flyTask.getId())
                    .eq("state", 0))));
            if (Objects.nonNull(userId)){
                flyTask.setUserName(userMap.get(userId).getNickName());
            }
            if (Objects.nonNull(pipelineId)){
                flyTask.setPipelineName(pipelineMap.get(pipelineId));
            }
            if (Objects.nonNull(telemetryUrl)){
                flyTask.setTelemetryUrl(ocsSimpleModel.getObjectUrl(telemetryUrl));
            }
            if (flyTask.getFlightState() == 1){
                flyTask.setLiveVideoUrl(getLiveVideoUrl(flyTask.getTaskSource(),flyTask.getTaskNumber(),flyTask.getUavId(),flyTask.getProjectId()));
            }
        });
        return modelPage;
    }

    private String getLiveVideoUrl(Integer taskSource, String taskNumber, String uavId,Integer projectId) {
        if (taskSource == 2){
            if (YkClient.YK_CHANNEL_MAP.containsKey(projectId)){
                ModelMap boxLiveVideoUrl = HttpRequest.getLiveTaskVideoFromYuKong(
                        appConstants.yuKongHttpHost, YkClient.YK_PROJECT_ID_TOKEN_MAP.get(projectId),String.valueOf(taskNumber));
                String videoUrl = (String) boxLiveVideoUrl.get("rtmp");
                if (Objects.isNull(videoUrl)){
                    return null;
                }
                return videoUrl;
            }else {
                return null;
            }
        }
        return null;
    }

    /**
     * 删除一个任务
     *
     * @param queryMo 参数集[实体ID 与 项目ID, 数据状态等]
     * @return 是否操作成功
     */
    @Override
    public boolean delete(QueryMo queryMo) {
        if(Objects.isNull(queryMo.getEqMap().get("id"))){
            return false;
        }
        return 1 == flyTaskMapper.delete(new QueryWrapper<FlyTask>().allEq(queryMo.getEqMap()));
    }

    /**
     * 通过ID更新一条数据
     *
     * @param operateMo 实体
     * @return 是否操作成功
     */
    @Override
    public boolean update(OperateMo operateMo) {
        ObjectMapper objectMapper = new ObjectMapper();
        FlyTask flyTask = objectMapper.convertValue(operateMo.getEntity(), FlyTask.class);
        return 1 == flyTaskMapper.update(flyTask, new QueryWrapper<FlyTask>().allEq(operateMo.getEqMap()));
    }

    /**
     * 通过ID查询一条数据
     *
     * @param queryMo 参数集[实体ID 与 项目ID, 数据状态等]
     * @return 查询结果对象
     */
    @Override
    public FlyTask selectOne(QueryMo queryMo) {
        if(Objects.nonNull(queryMo.getEqMap().get("id"))){
            FlyTask flyTask = flyTaskMapper.selectOne(new QueryWrapper<FlyTask>().allEq(queryMo.getEqMap()));
            if (Objects.nonNull(flyTask) && Objects.nonNull(flyTask.getTelemetryUrl())){
                flyTask.setTelemetryUrl(ocsSimpleModel.getObjectUrl(flyTask.getTelemetryUrl()));
            }
            return flyTask;
        }
        return null;
    }

    /**
     * 插入一条数据
     *
     * @param operateMo 实体对象
     * @return 是否操作成功
     */
    @Override
    public boolean insert(OperateMo operateMo) {
        ObjectMapper objectMapper = new ObjectMapper();
        FlyTask flyTask = objectMapper.convertValue(operateMo.getEntity(), FlyTask.class);
        return 1 == flyTaskMapper.insert(flyTask);
    }

    /**
     * 通过ID逻辑删除一条数据
     *
     * @param queryMo 参数集[实体ID 与 项目ID, 数据状态]
     * @return 是否操作成功
     */
    @Override
    public boolean logicallyDelete(QueryMo queryMo) {
        return 1 == flyTaskMapper.update(
                new FlyTask().setState(1),
                new QueryWrapper<FlyTask>().allEq(queryMo.getEqMap())
        );
    }
}
